﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common;
using ResultManagement;
using System.Text;

namespace KnowFirstWebApplication
{
    public partial class Results : basePageSessionExpire
    {
        public const string USERNAME = "UserName";
        public const string CATEGORY = "Category";
        public const int NUMBER_OF_RESULTS_PER_PAGE = 20;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DisplayDocumentTypeList();
                //Session[USERNAME] = "roeyaus";
                ResultManager rm = new ResultManager("", HttpContext.Current.Server.MapPath("~/App_Data/HebrewPrefixes.txt"));
                User User = GetCurrentUser();
                PopulateDateCombos();
                DisplayUserCategoryNames(User);
                if (User.Categories.Count > 0)
                {
                    ViewState[CATEGORY] = User.Categories[0].Name;
                    lbCategories.SelectedIndex = 0;
                    List<Document> results = Document.SortDocumentsByPriorityDate(rm.GetUserCategoryResults(User.UserName, GetCurrentCategory(), true));
                    DisplayCategoryName(ViewState[CATEGORY] as string, NUMBER_OF_RESULTS_PER_PAGE, results.Count);
                    DisplayResults(results);
                    //PopulateDateCBs(Document.GetDocumentMinDate(results), Document.GetDocumentMaxDate(results));
                    PopulateDateCBs(DateTime.Now.Subtract(new TimeSpan(168, 0, 0)), DateTime.Now.Add(new TimeSpan(24,0,0)));
                }
             
            }
        }

        public void PopulateDateCBs(DateTime FromDate, DateTime ToDate)
        {
            cbFromYear.Text = FromDate.Year.ToString();
            cbFromMonth.Text = FromDate.Month.ToString();
            cbFromDay.Text = FromDate.Day.ToString();
            cbToYear.Text = ToDate.Year.ToString();
            cbToMonth.Text = ToDate.Month.ToString();
            cbToDay.Text = ToDate.Day.ToString();
        }

        public void DisplayResults(List<Document> results)
        {
            lvCategoryResults.DataSource = results;
            lvCategoryResults.DataBind();
        }

        public DateTime GetFromDate()
        {
            return new DateTime(Int32.Parse(cbFromYear.Text),
                Int32.Parse(cbFromMonth.Text), Int32.Parse(cbFromDay.Text));
        }
        public DateTime GetToDate()
        {
            return new DateTime(Int32.Parse(cbToYear.Text),
                Int32.Parse(cbToMonth.Text), Int32.Parse(cbToDay.Text));
        }

        User GetCurrentUser()
        {
            Dal.DatabaseAbstractionLayer dal = new Dal.DatabaseAbstractionLayer("");
            User User = dal.GetUserByUserName(Session[USERNAME] as string);
            return User;
        }

        Category GetCurrentCategory()
        {
            User User = GetCurrentUser();
            return User.GetCategoryByName(ViewState[CATEGORY] as string);
        }

        private void DisplayCurrentCategoryResults()
        {
            User User = GetCurrentUser();
            ResultManager rm = new ResultManager("", HttpContext.Current.Server.MapPath("~/App_Data/HebrewPrefixes.txt"));  
            List<Document> results = rm.GetUserCategoryResults(User.UserName, User.GetCategoryByName(ViewState[CATEGORY] as string), true);
            results = rm.FilterResultsByDocumentTypes(results, GetSelectedDocTypes());
            results = Document.FilterDocumentsByDate(results, GetFromDate(), GetToDate());
            DisplayCategoryName(ViewState[CATEGORY] as string, NUMBER_OF_RESULTS_PER_PAGE, results.Count);
            DisplayResults(Document.SortDocumentsByPriorityDate(results));
        }

        public void DisplayDocumentTypeList()
        {
            cblDocumentTypes.DataSource = Enum.GetNames(typeof(Document.Type));
            cblDocumentTypes.DataBind();
            foreach (ListItem li in cblDocumentTypes.Items)
                li.Selected = true;
        }

        private void DisplayCategoryName(string categoryName, int numResPerPage, 
            int totNumRes)
        {

            lblCategoryName.Text = String.Format("קטגוריה: {0}, מציג {3}-{1} תוצאות מתוך {2}. ", categoryName,
                ResultsDataPager.StartRowIndex, totNumRes, ResultsDataPager.StartRowIndex + ResultsDataPager.PageSize);
            lblCategoryName.Font.Bold = true;
        }

        private void DisplayUserCategoryNames(User User)
        {
            lbCategories.Items.Clear();
            lbCategories.DataSource = User.Categories;
            lbCategories.DataBind();
        }

        private List<Document.Type> GetSelectedDocTypes()
        {
            List<Document.Type> docTypes = new List<Document.Type>();
            foreach (ListItem li in cblDocumentTypes.Items)
            {
                if (li.Selected)
                    docTypes.Add((Document.Type)Enum.Parse(typeof(Document.Type), li.Text, true));
            }
            return docTypes;
        }


        public void PopulateDateCombos()
        {
            cbFromDay.DataSource = UIHelper.GetDaysInMonth();
            cbFromDay.DataBind();
            cbFromMonth.DataSource = UIHelper.GetMonthesInYear();
            cbFromMonth.DataBind();
            cbFromYear.DataSource = UIHelper.GetYearsFrom1990To2020();
            cbFromYear.DataBind();
            cbToDay.DataSource = UIHelper.GetDaysInMonth();
            cbToDay.DataBind();
            cbToMonth.DataSource = UIHelper.GetMonthesInYear();
            cbToMonth.DataBind();
            cbToYear.DataSource = UIHelper.GetYearsFrom1990To2020();
            cbToYear.DataBind();

        }

        protected void btnLoadCategory_Click(object sender, EventArgs e)
        {
            ViewState[CATEGORY] = lbCategories.SelectedValue;
            DisplayCurrentCategoryResults();
        }
        protected void lvCategoryResults_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
        {
            ResultsDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
            DisplayCurrentCategoryResults();
        }

        protected void cblDocumentTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState[CATEGORY] = lbCategories.SelectedValue;
            DisplayCurrentCategoryResults();
        }

    }
}
